package com.hyd.tweet.xmpp;

import com.google.appengine.api.xmpp.JID;
import com.hyd.tweet.AppException;
import com.hyd.tweet.Application;
import com.hyd.tweet.twitter.CommandProcessor;
import com.hyd.tweet.user.User;
import com.hyd.tweet.user.UserManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import twitter4j.TwitterException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 自动更新用户的 Timeline
 *
 * @author yiding.he
 */
public class TwitterUpdaterServlet extends HttpServlet {

    static final Logger log = LoggerFactory.getLogger(TwitterUpdaterServlet.class);

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        update();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        update();
    }

    public static void update() {

        if (!Application.getEnabled().equals("true")) {
            return;
        }

        try {
            List<String> accounts = UserManager.next(20);

            for (String account : accounts) {
                processUser(account);
            }
        } catch (Exception e) {
            log.error("自动发送消息失败", e);
        }
    }

    private static void processUser(String account) {

        User user = UserManager.getUser(account);

        try {
            // 检查用户状态
            if (user == null || !user.isReceivingMessage()) {
                return;
            }

            JID jid = new JID(user.getAccount());

            // 如果用户设置为自动接收消息，且关闭了所有客户端，则结束对该用户的处理
            if ("auto".equals(user.getMessageStatus()) && !XMPPMessageSender.isAvailable(jid)) {
                log.info(jid + " is not available.");
                return;
            }

            XMPPMessageSender.sendMessages(jid, CommandProcessor.process("/u auto", user));

        } catch (Exception e) {
            if (e instanceof AppException &&
                    e.getCause() instanceof TwitterException &&
                    ((TwitterException) e.getCause()).getStatusCode() == 401) {
                log.error("用户 " + account + " 的授权信息不再有效，已删除。", e);
                UserManager.deleteUser(account);
            }

            log.error("发送给" + account + "消息失败", e);
        }
    }
}
